package com.luyuan.crm.task.internal;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Order;

import com.luyuan.crm.member.model.Customer;
import com.luyuan.crm.task.TaskDaily;
import com.luyuan.crm.task.TaskDailyService;
import com.luyuan.crm.task.TaskDailyStatus;
import com.luyuan.crm.user.Party;
import com.ruijie.foundation.dao.support.HibernateEntityDao;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaQueryTemplate;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;
import com.ruijie.foundation.security.AppUserContext;

public class TaskDailyServiceImpl extends HibernateEntityDao<TaskDaily> implements TaskDailyService {

    @Override
    public TaskDaily getTaskDailyById(String id) {
        return get(id);
    }

    @Override
    public void createTaskDaily(TaskDaily taskDaily) {
        taskDaily.setCreator(AppUserContext.getCurrentUsername());
        taskDaily.setCreateTime(new Date());
        taskDaily.setTaskStatus(TaskDailyStatus.CREATED);
        save(taskDaily);
    }

    @Override
    public void cancelTaskDaily(TaskDaily taskDaily) {
        update("update TaskDaily set taskStatus = ? where id = ? ",
                new Object[] { TaskDailyStatus.CANCELLED, taskDaily.getId() });
    }

    @Override
    public void excuteTaskDaily(TaskDaily taskDaily) {
        update("update TaskDaily set  taskStatus = ?, executionTime = ? where id = ? ", new Object[] {
                TaskDailyStatus.EXECUTED, new Date(), taskDaily.getId() });
    }

    @Override
    public Page pagedQuery(CriteriaTemplate criteria, int pageNo, int pageSize, List<Order> orders) {
        if (orders.isEmpty()) {
            orders.add(Order.asc("expectedTime"));
        }
        CriteriaQueryTemplate cqt = new CriteriaQueryTemplate(getSessionFactory());
        return cqt.pagedQuery(criteria, pageNo, pageSize, orders);
    }

    @Override
    public void updateTaskDaily(TaskDaily taskDaily) {
        update(taskDaily);
    }

    @Override
    public void updateTaskDailyParty(Customer customer, Party party) {
        update("update TaskDaily set party = ? where customer = ?", new Object[] { party, customer });
    }

    @Override
    public void clearTaskDaily() {
        Calendar ca = Calendar.getInstance();// 得到一个Calendar的实例
        ca.setTime(new Date()); // 设置时间为当前时间
        ca.add(Calendar.YEAR, -1); // 年份减1
        Date lastMonth = ca.getTime(); // 结果
        logger.info("clean TaskDaily before: " + lastMonth);
        update("delete TaskDaily where executionTime < ?", lastMonth);
    }
}
